//
//  LocationVC.m
//  AILock
//
//  Created by 谭亚明 on 2020/7/26.
//  Copyright © 2020 tym. All rights reserved.
//

#import "LocationVC.h"
#import "Sizes.h"
#import "ZHFAddTitleAddressView.h"
#import "UIView+ZFFrame.h"
#import <AMapLocationKit/AMapLocationKit.h>
#import <MAMapKit/MAMapKit.h>
#import "LocationTopView.h"
#import "BRAddressPickerView.h"
#import "LocationBottomView.h"
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AMapSearchKit/AMapSearchKit.h>
#import <AMapSearchKit/AMapSearchKit.h>

@interface LocationVC ()<AMapSearchDelegate,AMapLocationManagerDelegate,MAMapViewDelegate>
@property(nonatomic,strong)ZHFAddTitleAddressView * addTitleAddressView;

@property(nonatomic,strong) MAMapView * mapView ;
@property(nonatomic,strong) AMapSearchAPI *search;
@property(nonatomic,strong) AMapLocationManager *locationManager;

@property(nonatomic,strong) LocationTopView *topView;
@property(nonatomic,strong) LocationBottomView *bottomView;

@property(nonatomic,strong) TYMButton *locationBtn;
@property(nonatomic,strong) UIImageView *centImage;

@property(nonatomic,strong) AMapLocationReGeocode *regeo;
//@property(nonatomic,copy) NSString *shengStr;
//@property(nonatomic,copy) NSString *shiStr;
//@property(nonatomic,copy) NSString *quStr;
@end

@implementation LocationVC

-(instancetype)init{
    self =[super init];
    [AMapServices sharedServices].apiKey =@"14c870050c7a93a7c229ecba91cac05b";
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [AMapServices sharedServices].enableHTTPS = YES;
    self.mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight - 317)];
    _mapView.showsUserLocation = YES;
    _mapView.delegate = self;
    _mapView.logoCenter =  CGPointMake(ScreenWidth/2, 35+SafeTopMargin + 15);
    _mapView.showsScale = NO;
    _mapView.showsCompass = NO;
    _mapView.userTrackingMode = MAUserTrackingModeFollow;
    [self.view addSubview:_mapView];

    self.search = [[AMapSearchAPI alloc] init];
    self.search.delegate = self;

    self.locationManager = [[AMapLocationManager alloc] init];
    [self.locationManager setDelegate:self];
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
    self.locationManager.locationTimeout =2;
    self.locationManager.reGeocodeTimeout = 2;
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
    self.locationManager.locationTimeout =2;
    self.locationManager.reGeocodeTimeout = 2;
    
    _topView = [LocationTopView getLocationTopView];
    _topView.frame = CGRectMake(10, 35+SafeTopMargin , ScreenWidth-20, 49);
    _topView.layer.masksToBounds = YES;
    _topView.layer.cornerRadius = 5;
    TYMWeak(self);
    _topView.closeViewBlock = ^{
        [weakself.navigationController popViewControllerAnimated:YES];
    };
    _topView.seleCityBlock = ^{
        [weakself touchesBegan:nil withEvent:nil];
        [weakself.addTitleAddressView addAnimate];
    };
    _topView.editEndBlock = ^(NSString * _Nonnull fidStr) {
        [weakself setMapViewWithPOIKeywordsSearch:fidStr];
    };
    [self.view addSubview:_topView];
    
    _bottomView = [LocationBottomView getLocationBottomView];
    _bottomView.frame = CGRectMake(0,_mapView.zf_bottom, ScreenWidth, _bottomView.zf_height);
    _bottomView.seleIndexBlock = ^(AMapPOI *poi) {
        if (!weakself.regeo) {
            [WHToast showMessage:@"系统定位中..." duration:2 finishHandler:nil];
            return;
        }
        if(weakself.seleAddressBlock){
            weakself.seleAddressBlock(poi,weakself.regeo);
        }
        [weakself.navigationController popViewControllerAnimated:YES];
    };
    _bottomView.tableSeleBlock = ^(AMapPOI * _Nonnull poi) {
        [weakself.mapView setCenterCoordinate:CLLocationCoordinate2DMake(poi.location.latitude, poi.location.longitude) animated:YES];
    };
    [self.view addSubview:_bottomView];
    
    self.locationBtn.frame = CGRectMake(ScreenWidth - 32-15, ScreenHeight - 317-32-15, 32, 32);
    [self.view addSubview:self.locationBtn];
    
    self.addTitleAddressView = [[ZHFAddTitleAddressView alloc]init];
    self.addTitleAddressView.title = @"选择地址";
    self.addTitleAddressView.delegate1 = self;
    self.addTitleAddressView.defaultHeight = 350;
    self.addTitleAddressView.titleScrollViewH = 30;
    if (self.addTitleAddressView.titleIDMarr.count > 0) {
        self.addTitleAddressView.isChangeAddress = true;
    }
    else{
        self.addTitleAddressView.isChangeAddress = false;
    }
    [self.view addSubview:[self.addTitleAddressView initAddressView]];
    self.centImage.frame = CGRectMake(ScreenWidth/2 - 12, (ScreenHeight-317)/2, 27, 38);
    [self.mapView addSubview:self.centImage];
    
    [self startLocation];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
}

//开始定位
- (void)startLocation {
    __weak typeof(self) weakSelf = self;
    [self.locationManager requestLocationWithReGeocode:YES completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
        if (error) {
            return;
        }
        //设置地图
        [weakSelf.mapView setZoomLevel:15.5 animated:YES];
        [weakSelf.mapView setCenterCoordinate:location.coordinate animated:NO];
        [weakSelf setMapViewWithCLLocationCoordinate2D:location.coordinate];
        self.topView.cityStr = regeocode.city;
        self.regeo = regeocode;
    }];
    
}

-(void)cancelBtnClick:(NSString *)titleAddress titleID:(NSString *)titleID{
    if (titleAddress.length>5) {
        NSArray *citys = [[titleAddress substringFromIndex:1] componentsSeparatedByString:@" "];
        if (citys.count) {
            self.topView.cityStr = citys[1];
            [self setMapViewWithPOIKeywordsSearch:citys[2]];
        }
    }
}


-(void)setMapViewWithPOIKeywordsSearch:(NSString*)words{
    
    AMapPOIKeywordsSearchRequest *request = [[AMapPOIKeywordsSearchRequest alloc] init];
        
    request.keywords            = words;
    request.city                = self.topView.cityStr;
    //request.types               = @"高等院校";
    request.requireExtension    = YES;
    request.cityLimit           = YES;
    request.requireSubPOIs      = YES;
    [self.search AMapPOIKeywordsSearch:request];
}

//地图区域改变完成后会调用此接口
- (void)mapView:(MAMapView *)mapView regionDidChangeAnimated:(BOOL)animated {
    
    [self setMapViewWithCLLocationCoordinate2D: mapView.centerCoordinate];
}


//根据坐标来搜索附近的地址
-(void)setMapViewWithCLLocationCoordinate2D:(CLLocationCoordinate2D)userLocation2D{
    AMapPOIAroundSearchRequest *request = [[AMapPOIAroundSearchRequest alloc] init];
    request.sortrule = 0;
    request.offset = 30;
    request.location = [AMapGeoPoint locationWithLatitude:userLocation2D.latitude longitude:userLocation2D.longitude];
    request.radius = 500;
    [self.search AMapPOIAroundSearch:request];
}

-(TYMButton*)locationBtn{
    if (_locationBtn == nil) {
        _locationBtn = [TYMButton btn_Image:@"icon_location2"];
        _locationBtn.backgroundColor = [UIColor whiteColor];
        _locationBtn.layer.masksToBounds = YES;
        _locationBtn.layer.cornerRadius = 5;
        [_locationBtn addTarget:self action:@selector(lcoationActionb:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _locationBtn;
}

-(UIImageView*)centImage{
    if (_centImage == nil) {
        _centImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon_tag1"]];
    }
    return _centImage;
}

-(void)lcoationActionb:(id)sender{
    [self startLocation];
    [self.mapView setCenterCoordinate:self.mapView.userLocation.location.coordinate animated:YES];
}

/* POI 搜索回调. */
- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response
{
    if (response.pois.count == 0)
    {
        return;
    }
    [self.bottomView setDataArray:response.pois];
}

@end
